package cn.tedu._05mvcboot4.controller;

import cn.tedu._05mvcboot4.common.response.JsonResult;
import cn.tedu._05mvcboot4.common.response.StatusCode;
import cn.tedu._05mvcboot4.mapper.UserMapper;
import cn.tedu._05mvcboot4.pojo.dto.UserArticleDTO;
import cn.tedu._05mvcboot4.pojo.dto.UserLoginDTO;
import cn.tedu._05mvcboot4.pojo.entity.Article;
import cn.tedu._05mvcboot4.pojo.vo.ArticleVO;
import cn.tedu._05mvcboot4.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Slf4j
@Validated
@RestController
@RequestMapping("/v1/users/")
@Api(tags = "用户登录模块")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @PostMapping("login")
    @ApiOperation("用户登录")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        log.debug("用户名:{},密码:{}", userLoginDTO.getUsername(),userLoginDTO.getPassword());
        UserVO userVO = userMapper.selectUser(userLoginDTO.getUsername(), userLoginDTO.getPassword());
        if (userVO == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }
        log.debug("用户信息:{}",userVO);
        session.setAttribute("user",userVO);
        return JsonResult.ok();
    }

    @PostMapping("article")
    @ApiOperation("发表文章")
    public JsonResult userArticle(@RequestBody @Validated UserArticleDTO userArticleDTO, @ApiIgnore HttpSession session){
        log.debug("用户发表文章:{}",userArticleDTO);
        UserVO userVO = (UserVO) session.getAttribute("user");
        Article article = new Article();
        BeanUtils.copyProperties(userArticleDTO,article);
        article.setUserId(userVO.getId());
        log.debug("用户发表文章存入:{}",article);
        userMapper.insertArticle(article);
        return JsonResult.ok();
    }

    @GetMapping("selectByArticleId")
    @ApiOperation("查询文章详情")
    @ApiImplicitParam(name = "id", value = "文章id", required = true, dataType = "int")
    public JsonResult selectByArticleId(@Range(min = 1, max = 100, message = "文章id必须在1~100之间") @RequestParam Integer id){
        log.debug("查询文章详情id:{}",id);
        ArticleVO articleVO = userMapper.selectByArticleId(id);
        if (articleVO == null){
            return new JsonResult(StatusCode.OPERATION_FAILED);
        }
        return JsonResult.ok(articleVO);
    }


}
